package com.le.tester.javaThink.fourth.concurrency;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/11/8 10:45
 * description：被阻塞的nio通道会自动的响应中断
 */

class NIOBlocked implements Runnable {

    private final SocketChannel sc;

    NIOBlocked(SocketChannel sc) {
        this.sc = sc;
    }

    @Override
    public void run() {
        try {
            System.out.println("Waiting for read() in" + this);
            //设置一个新的缓冲区的容量为1字节
            sc.read(ByteBuffer.allocate(1));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("Exiting NIOBlocked.run()" + this);
    }
}

public class NIOInterruption {
    public static void main(String[] args) throws Exception {
        //开启线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        ServerSocket server = new ServerSocket(9300);
        InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 9300);
        //打开两个channel
        SocketChannel sc1 = SocketChannel.open(isa);
        SocketChannel sc2 = SocketChannel.open(isa);
        Future<?> f = exec.submit(new NIOBlocked(sc1));
        exec.execute(new NIOBlocked(sc2));
        exec.shutdown();
        TimeUnit.SECONDS.sleep(1);
        f.cancel(true);
        TimeUnit.SECONDS.sleep(1);
        //sc1并没有close
        //释放阻塞中的channel
        sc2.close();

    }

}
